package com.tfswx.fljdmxyy.utils;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件工具
 *
 * @Author 陈文佳
 * @Date 2023/03/24
 */
public final class FileUtils {
    private FileUtils() {

    }

    public static void createDirByFilePath(String filePath) {
        Path file = Paths.get(filePath);
        createDirByFilePath(file);
    }

    public static void createDirByFilePath(Path filePath) {
        createDir(filePath.getParent());
    }

    public static void createDir(String dirPath) {
        createDir(Paths.get(dirPath));
    }

    public static void createDir(Path dirPath) {
        if (Files.exists(dirPath)) {
            return;
        }

        try {
            boolean success = dirPath.toFile().mkdirs();
            if (!success && !Files.exists(dirPath)) {
                throw new RuntimeException("目录创建失败：" + dirPath);
            }
        } catch (Exception e) {
            throw new RuntimeException("目录创建错误", e);
        }
    }

    /**
     * 将File转化为MultipartFile
     *
     * @param file
     * @return MultipartFile
     */
    public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int) file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

}
